<template>
  <div class="image-editor-container">
    <!-- 顶部导航栏 -->
    <el-header class="editor-header">
      <div class="logo">图片编辑器</div>
      <div class="editor-toolbar-btns">
        <el-upload
          class="upload-btn"
          action="#"
          :show-file-list="false"
          :on-change="handleImageUpload"
          accept="image/*"
        >
          <el-button type="primary" icon="Upload">上传图片</el-button>
        </el-upload>
        <el-button type="success" icon="Download" @click="downloadImage" :disabled="!imageLoaded">
          下载图片
        </el-button>
        <el-button
          type="warning"
          icon="UploadFilled"
          @click="showSaveDialog = true"
          :disabled="!imageLoaded"
        >
          保存图片
        </el-button>
      </div>
    </el-header>

    <!-- 主要内容区 -->
    <el-container class="editor-content">
      <!-- 左侧工具栏 -->
      <el-aside min-width="300px" class="editor-toolbar">
        <el-card>
          <el-tabs v-model="activeTab" class="toolbar-tabs">
            <!-- 基本编辑 -->
            <el-tab-pane label="基本编辑" name="basic">
              <div class="tool-section">
                <h3>尺寸调整</h3>
                <el-input-number
                  v-model="imageWidth"
                  :min="1"
                  :max="4000"
                  label="宽度"
                  @change="updateImageSize"
                ></el-input-number>
                <el-input-number
                  v-model="imageHeight"
                  :min="1"
                  :max="4000"
                  label="高度"
                  @change="updateImageSize"
                ></el-input-number>
              </div>

              <div class="tool-section">
                <h3>旋转</h3>
                <div class="rotation-controls">
                  <el-button @click="rotateImage(-90)" size="small">向左</el-button>
                  <el-button @click="rotateImage(90)" size="small">向右</el-button>
                  <el-button @click="rotateImage(180)" size="small">旋转180度</el-button>
                </div>
              </div>

              <div class="tool-section">
                <h3>翻转</h3>
                <div class="flip-controls">
                  <el-button @click="flipImage('horizontal')" size="small"> 水平翻转 </el-button>
                  <el-button @click="flipImage('vertical')" size="small"> 垂直翻转 </el-button>
                </div>
              </div>
            </el-tab-pane>

            <!-- 色彩调整 -->
            <el-tab-pane label="色彩调整" name="color">
              <div class="tool-section">
                <h3>亮度</h3>
                <el-slider
                  v-model="brightness"
                  :min="0"
                  :max="200"
                  :step="1"
                  @change="updateImageEffects"
                ></el-slider>
                <span class="slider-value">{{ brightness }}%</span>
              </div>

              <div class="tool-section">
                <h3>对比度</h3>
                <el-slider
                  v-model="contrast"
                  :min="0"
                  :max="200"
                  :step="1"
                  @change="updateImageEffects"
                ></el-slider>
                <span class="slider-value">{{ contrast }}%</span>
              </div>

              <div class="tool-section">
                <h3>饱和度</h3>
                <el-slider
                  v-model="saturation"
                  :min="0"
                  :max="200"
                  :step="1"
                  @change="updateImageEffects"
                ></el-slider>
                <span class="slider-value">{{ saturation }}%</span>
              </div>

              <div class="tool-section">
                <h3>滤镜</h3>
                <el-select v-model="filter" @change="updateImageEffects">
                  <el-option label="无" value="none"></el-option>
                  <el-option label="黑白" value="grayscale(100%)"></el-option>
                  <el-option label="复古" value="sepia(100%)"></el-option>
                  <el-option label="反色" value="invert(100%)"></el-option>
                  <el-option label="蓝色调" value="hue-rotate(180deg)"></el-option>
                  <el-option label="暖色调" value="hue-rotate(30deg)"></el-option>
                </el-select>
              </div>
            </el-tab-pane>

            <!-- 文字添加 -->
            <el-tab-pane label="添加文字" name="text">
              <div class="tool-section">
                <el-input v-model="textContent" placeholder="输入文字内容"></el-input>

                <el-color-picker v-model="textColor" label="文字颜色"></el-color-picker>

                <el-input-number
                  v-model="textSize"
                  :min="12"
                  :max="120"
                  label="文字大小"
                  :step="2"
                ></el-input-number>

                <el-select v-model="textAlign">
                  <el-option label="左对齐" value="left"></el-option>
                  <el-option label="居中" value="center"></el-option>
                  <el-option label="右对齐" value="right"></el-option>
                </el-select>

                <el-button type="primary" @click="addText" :disabled="!textContent.trim()">
                  添加到图片
                </el-button>
              </div>

              <div class="added-texts">
                <h3>已添加文字</h3>
                <div v-if="textLayers.length">
                  <div v-for="(text, index) in textLayers" :key="index" class="text-item">
                    <span>{{ text.content }}</span>
                    <el-button
                      icon="Delete"
                      size="mini"
                      @click="removeText(index)"
                      type="text"
                    ></el-button>
                  </div>
                </div>
                <p v-else class="empty-text">暂无添加的文字</p>
              </div>
            </el-tab-pane>

            <!-- 贴图添加 -->
            <el-tab-pane label="添加贴图" name="sticker">
              <div class="tool-section">
                <h3>选择贴图</h3>
                <div class="sticker-library">
                  <div
                    v-for="(sticker, index) in stickerLibrary"
                    :key="index"
                    class="sticker-item"
                    @click="selectSticker(index)"
                    :class="{ selected: selectedStickerIndex === index }"
                  >
                    <img :src="sticker" alt="贴图选项" class="sticker-thumb" />
                  </div>
                </div>

                <el-input-number
                  v-model="stickerSize"
                  :min="20"
                  :max="300"
                  label="贴图大小"
                  :step="10"
                ></el-input-number>

                <el-button
                  type="primary"
                  @click="addSticker"
                  :disabled="selectedStickerIndex === -1"
                >
                  添加到图片
                </el-button>
              </div>

              <div class="added-stickers">
                <h3>已添加贴图</h3>
                <div v-if="stickerLayers.length">
                  <div v-for="(sticker, index) in stickerLayers" :key="index" class="sticker-item">
                    <img :src="sticker.src" alt="已添加的贴图" class="sticker-thumb" />
                    <el-button
                      icon="Delete"
                      size="mini"
                      @click="removeSticker(index)"
                      type="text"
                    ></el-button>
                  </div>
                </div>
                <p v-else class="empty-text">暂无添加的贴图</p>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-aside>

      <!-- 中间编辑区 -->
      <el-main class="editor-workspace">
        <div class="workspace-container">
          <div v-if="!imageLoaded" class="placeholder-container">
            <el-empty description="请上传一张图片开始编辑" :image-size="100"></el-empty>
          </div>

          <div v-else class="image-container">
            <div class="edited-image" :style="computedImageStyles" ref="imageContainer">
              <img
                :src="originalImage"
                alt="编辑中的图片"
                class="original-image"
                :style="computedOriginalImageStyles"
              />

              <!-- 文字图层 -->
              <div
                v-for="(text, index) in textLayers"
                :key="'text-' + index"
                class="text-layer"
                :style="{
                  color: text.color,
                  fontSize: text.size + 'px',
                  textAlign: text.align,
                  top: text.y + 'px',
                  left: text.x + 'px',
                  position: 'absolute',
                }"
                :data-index="index"
                @mousedown="startDragging('text', index, $event)"
              >
                {{ text.content }}
              </div>

              <!-- 贴图图层 -->
              <div
                v-for="(sticker, index) in stickerLayers"
                :key="'sticker-' + index"
                class="sticker-layer"
                :style="{
                  width: sticker.size + 'px',
                  height: sticker.size + 'px',
                  top: sticker.y + 'px',
                  left: sticker.x + 'px',
                  position: 'absolute',
                }"
                :data-index="index"
                @mousedown="startDragging('sticker', index, $event)"
              >
                <img :src="sticker.src" alt="贴图" class="sticker-img" />
              </div>
            </div>
          </div>
        </div>
      </el-main>

      <!-- 右侧历史记录 -->
      <el-aside width="300px" class="editor-history">
        <el-card>
          <template v-slot:header>
            <div class="history-header">
              <h3>操作历史</h3>
              <el-button
                icon="RefreshLeft"
                size="mini"
                @click="resetEditor"
                :disabled="!imageLoaded"
              >
                重置
              </el-button>
            </div>
          </template>

          <!-- 只显示当前有效历史记录 -->
          <el-timeline>
            <el-timeline-item
              v-for="(item, index) in displayedHistory"
              :key="index"
              :timestamp="formatTime(item.time)"
              placement="top"
              :class="{ 'inactive-history': index > historyIndex }"
            >
              <span class="history-action" :title="item.action">{{ item.action }}</span>
            </el-timeline-item>
          </el-timeline>

          <div class="history-controls" v-if="isHistoryAvailable">
            <el-button @click="undo" :disabled="!canUndo" size="small" icon="ArrowLeft">
              撤销
            </el-button>
            <el-button @click="redo" :disabled="!canRedo" size="small" icon="ArrowRight">
              重做
            </el-button>
          </div>
        </el-card>
      </el-aside>
    </el-container>
  </div>

  <!-- 保存图片对话框 -->
  <el-dialog v-model="showSaveDialog" title="保存图片" width="500px">
    <el-form ref="saveFormRef" :model="saveForm" label-width="80px">
      <el-form-item label="图片id">
        <el-input v-model="saveForm.id" placeholder="请输入图片id" disabled></el-input>
      </el-form-item>
      <el-form-item label="空间选择">
        <el-select v-model="saveForm.spaceId" placeholder="请选择空间">
          <el-option label="公共图库" :value="null" />
          <el-option
            v-for="item in spaceList"
            :key="item.id"
            :label="item.spaceName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="图片名称">
        <el-input v-model="saveForm.name" placeholder="请输入图片名称"></el-input>
      </el-form-item>
      <el-form-item label="图片分类">
        <el-select v-model="saveForm.classifyId" placeholder="请选择图片分类">
          <el-option
            v-for="item in classifyStore.classifies"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图片标签">
        <el-select
          v-model="saveForm.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请输入标签"
        />
      </el-form-item>
      <el-form-item label="图片描述">
        <el-input v-model="saveForm.introduction" placeholder="请输入图片描述"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="showSaveDialog = false">取消</el-button>
      <el-button type="primary" @click="saveImageToServer">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadPictureAPI, getPictureByIdAPI } from '@/api/pictureAPI'
import { listSpaceByUserIdAPI } from '@/api/spaceAPI'
import { useRoute } from 'vue-router'
import { useClassifyStore } from '@/stores/classify'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const pictureId = route.query.pictureId

const classifyStore = useClassifyStore()
const userStore = useUserStore()

const showSaveDialog = ref(false)

const activeImage = ref(null)

const saveFormRef = ref(null)

const saveForm = reactive({
  id: pictureId || null,
  name: '', // 图片名称
  introduction: '', // 图片介绍
  classifyId: null, // 分类ID
  tags: ['编辑', '自定义'], // 图片标签
  spaceId: null, // 空间ID
})

const spaceList = ref([])

const listSpaceByUserId = async () => {
  if (!userStore.userInfo.id) return
  const res = await listSpaceByUserIdAPI()
  spaceList.value = res.data
}

const getPictureById = async () => {
  console.log('获取图片详情，ID:', pictureId)

  if (!pictureId) return
  const res = await getPictureByIdAPI(pictureId)
  console.log('获取图片详情结果:', res)
  activeImage.value = res.data
  saveForm.name = res.data.name
  saveForm.introduction = res.data.introduction
  saveForm.spaceId = res.data.spaceId
  saveForm.spaceName = res.data.spaceName
  saveForm.classifyId = res.data.classifyId
  originalImage.value = res.data.url
  imageLoaded.value = true
  addHistory('上传图片')
  imageWidth.value = res.data.picWidth
  imageHeight.value = res.data.picHeight
}

onMounted(() => {
  listSpaceByUserId()
  getPictureById()
})

// 初始化所有状态变量
const originalImage = ref('')
const imageLoaded = ref(false)
const imageWidth = ref(0)
const imageHeight = ref(0)
const rotation = ref(0)
const flipState = ref({ horizontal: false, vertical: false }) // 翻转状态
const brightness = ref(100)
const contrast = ref(100)
const saturation = ref(100)
const filter = ref('none')
const activeTab = ref('basic')
const imageContainer = ref(null)

// 文字相关
const textContent = ref('')
const textColor = ref('#000000')
const textSize = ref(24)
const textAlign = ref('center')
const textLayers = ref([])

// 贴图相关
const stickerLibrary = ref([
  'https://picsum.photos/seed/sticker1/100',
  'https://picsum.photos/seed/sticker2/100',
  'https://picsum.photos/seed/sticker3/100',
  'https://picsum.photos/seed/sticker4/100',
  'https://picsum.photos/seed/sticker5/100',
  'https://picsum.photos/seed/sticker6/100',
])
const selectedStickerIndex = ref(-1) // 默认为-1表示没有选中
const stickerSize = ref(100)
const stickerLayers = ref([])

// 拖拽相关
const dragging = ref({
  active: false,
  type: '',
  index: -1,
  offsetX: 0,
  offsetY: 0,
})

// 历史记录
const history = ref([])
const historyIndex = ref(-1)

// 计算属性：显示的历史记录（只显示当前有效部分）
const displayedHistory = computed(() => {
  if (!Array.isArray(history.value)) return []
  return history.value.slice(0, historyIndex.value + 1)
})

// 计算属性：历史记录可用性
const isHistoryAvailable = computed(() => {
  return Array.isArray(displayedHistory.value) && displayedHistory.value.length > 0
})

// 计算属性：是否可以撤销
const canUndo = computed(() => {
  return Number.isInteger(historyIndex.value) && historyIndex.value > 0
})

// 计算属性：是否可以重做
const canRedo = computed(() => {
  return (
    Number.isInteger(historyIndex.value) &&
    Array.isArray(history.value) &&
    historyIndex.value < history.value.length - 1
  )
})

// 计算属性 - 图片样式
const computedImageStyles = computed(() => {
  const safeWidth = isNaN(imageWidth.value) || imageWidth.value <= 0 ? 300 : imageWidth.value
  const safeHeight = isNaN(imageHeight.value) || imageHeight.value <= 0 ? 200 : imageHeight.value

  return {
    width: `${safeWidth}px`,
    height: `${safeHeight}px`,
    position: 'relative',
    overflow: 'hidden',
    margin: '0 auto',
  }
})

// 计算属性 - 原始图片样式（包含变换）
const computedOriginalImageStyles = computed(() => {
  const safeBrightness = isNaN(brightness.value) ? 100 : brightness.value
  const safeContrast = isNaN(contrast.value) ? 100 : contrast.value
  const safeSaturation = isNaN(saturation.value) ? 100 : saturation.value

  let filterStr = ''
  if (filter.value && filter.value !== 'none') {
    filterStr += `${filter.value} `
  }
  filterStr += `brightness(${safeBrightness}%) contrast(${safeContrast}%) saturate(${safeSaturation}%)`

  return {
    filter: filterStr,
    transform: `
      rotate(${rotation.value}deg)
      scaleX(${flipState.value?.horizontal ? -1 : 1})
      scaleY(${flipState.value?.vertical ? -1 : 1})
    `,
    width: '100%',
    height: '100%',
    objectFit: 'contain',
    transition: 'transform 0.3s ease',
  }
})

// 处理图片上传
const handleImageUpload = (rawFile) => {
  if (!rawFile || !rawFile.raw) {
    ElMessage.error('无效的图片文件')
    return
  }

  const reader = new FileReader()
  reader.readAsDataURL(rawFile.raw)
  reader.onload = (e) => {
    if (!e.target || !e.target.result) {
      ElMessage.error('图片读取失败')
      return
    }

    const img = new Image()
    img.src = e.target.result
    img.onload = () => {
      originalImage.value = e.target.result
      imageWidth.value = Math.max(1, img.width || 300)
      imageHeight.value = Math.max(1, img.height || 200)
      imageLoaded.value = true

      // 重置历史记录系统
      resetHistory()
      addHistory('上传图片')
      ElMessage.success('图片上传成功')
    }

    img.onerror = () => {
      ElMessage.error('无法加载图片')
    }
  }

  reader.onerror = () => {
    ElMessage.error('文件读取错误')
  }
}

// 重置历史记录系统
const resetHistory = () => {
  history.value = []
  historyIndex.value = -1
}

// 重置编辑器状态
const resetEditorState = () => {
  rotation.value = 0
  flipState.value = { horizontal: false, vertical: false }
  brightness.value = 100
  contrast.value = 100
  saturation.value = 100
  filter.value = 'none'
  textLayers.value = []
  stickerLayers.value = []
  textContent.value = ''
  selectedStickerIndex.value = -1

  resetHistory()
}

// 完全重置编辑器
const resetEditor = () => {
  if (imageLoaded.value) {
    const currentSrc = originalImage.value
    resetEditorState()
    originalImage.value = currentSrc
    addHistory('重置编辑')
    ElMessage.info('已重置所有编辑操作')
  }
}

// 更新图片尺寸
const updateImageSize = (value) => {
  if (!imageLoaded.value || isNaN(value)) return
  imageWidth.value = Math.max(1, Math.min(4000, imageWidth.value))
  imageHeight.value = Math.max(1, Math.min(4000, imageHeight.value))

  addHistory(`调整尺寸为 ${imageWidth.value}x${imageHeight.value}`)
}

// 旋转图片
const rotateImage = (degrees) => {
  if (!imageLoaded.value || isNaN(degrees)) return

  rotation.value = (rotation.value + degrees) % 360
  addHistory(`旋转 ${degrees} 度`)
}

// 翻转图片
const flipImage = (direction) => {
  if (!imageLoaded.value || !['horizontal', 'vertical'].includes(direction)) return

  flipState.value[direction] = !flipState.value[direction]
  addHistory(direction === 'horizontal' ? '水平翻转' : '垂直翻转')
}

// 更新图片效果
const updateImageEffects = () => {
  if (!imageLoaded.value) return

  let action = ''
  if (filter.value !== 'none') {
    action = `应用滤镜: ${filter.value}`
  } else {
    action = `调整色彩参数`
  }

  addHistory(action)
}

// 添加文字 - 修复历史记录文字内容显示
const addText = () => {
  if (!imageLoaded.value || !textContent.value.trim()) return

  const centerX = isNaN(imageWidth.value) ? 150 : imageWidth.value / 2
  const centerY = isNaN(imageHeight.value) ? 100 : imageHeight.value / 2

  // 保存原始文本内容用于历史记录
  const textToAdd = textContent.value.trim()

  textLayers.value.push({
    content: textToAdd,
    color: textColor.value,
    size: Math.max(12, Math.min(120, textSize.value)),
    align: textAlign.value,
    x: centerX,
    y: centerY,
  })

  nextTick(() => {
    // 显示完整的文字内容，不截断
    addHistory(`添加文字: ${textToAdd}`)
  })

  textContent.value = ''
}

// 移除文字 - 修复历史记录文字内容显示
const removeText = (index) => {
  if (isNaN(index) || index < 0 || index >= textLayers.value.length) return

  const removedText = textLayers.value[index].content || '未知文字'
  textLayers.value.splice(index, 1)
  // 显示完整的被移除文字内容
  addHistory(`移除文字: ${removedText}`)
}

// 选择贴图
const selectSticker = (index) => {
  if (isNaN(index) || index < 0 || index >= stickerLibrary.value.length) return

  selectedStickerIndex.value = index
}

// 添加贴图
const addSticker = () => {
  if (!imageLoaded.value || selectedStickerIndex.value === -1) return

  const safeWidth = isNaN(imageWidth.value) ? 300 : imageWidth.value
  const safeHeight = isNaN(imageHeight.value) ? 200 : imageHeight.value
  const safeSize = Math.max(20, Math.min(300, stickerSize.value))

  const centerX = safeWidth / 2 - safeSize / 2
  const centerY = safeHeight / 2 - safeSize / 2

  const stickerSrc = stickerLibrary.value[selectedStickerIndex.value]
  stickerLayers.value.push({
    src: stickerSrc,
    size: safeSize,
    x: centerX,
    y: centerY,
  })

  nextTick(() => {
    addHistory(`添加贴图 #${selectedStickerIndex.value + 1}`)
  })
}

// 移除贴图
const removeSticker = (index) => {
  if (isNaN(index) || index < 0 || index >= stickerLayers.value.length) return

  stickerLayers.value.splice(index, 1)
  addHistory(`移除贴图 #${index + 1}`)
}

// 开始拖拽
const startDragging = (type, index, e) => {
  if (!type || isNaN(index) || index < 0 || !e) return

  e.preventDefault()

  if (!imageContainer.value) return
  const element = e.target.closest(`.${type}-layer`)
  if (!element) return

  const elementRect = element.getBoundingClientRect()

  dragging.value = {
    active: true,
    type,
    index,
    offsetX: e.clientX - elementRect.left,
    offsetY: e.clientY - elementRect.top,
  }

  document.addEventListener('mousemove', handleDragMove)
  document.addEventListener('mouseup', stopDragging)
}

// 处理拖拽移动 - 优化历史记录描述
const handleDragMove = (e) => {
  if (!dragging.value.active || !e) return

  if (!imageContainer.value) return
  const containerRect = imageContainer.value.getBoundingClientRect()

  let newX = e.clientX - containerRect.left - dragging.value.offsetX
  let newY = e.clientY - containerRect.top - dragging.value.offsetY

  newX = Math.max(0, Math.min(newX, containerRect.width || 300))
  newY = Math.max(0, Math.min(newY, containerRect.height || 200))

  if (dragging.value.type === 'text' && textLayers.value[dragging.value.index]) {
    textLayers.value[dragging.value.index].x = newX
    textLayers.value[dragging.value.index].y = newY
  } else if (dragging.value.type === 'sticker' && stickerLayers.value[dragging.value.index]) {
    stickerLayers.value[dragging.value.index].x = newX
    stickerLayers.value[dragging.value.index].y = newY
  }
}

// 停止拖拽 - 优化历史记录描述
const stopDragging = () => {
  if (dragging.value.active) {
    let action = ''
    if (dragging.value.type === 'text' && textLayers.value[dragging.value.index]) {
      // 包含文字内容在历史记录中
      const text = textLayers.value[dragging.value.index].content || '文字'
      action = `移动文字: ${text.substring(0, 15)}${text.length > 15 ? '...' : ''}`
    } else if (dragging.value.type === 'sticker') {
      action = `移动贴图 #${dragging.value.index + 1}`
    }

    addHistory(action)

    dragging.value = {
      active: false,
      type: '',
      index: -1,
      offsetX: 0,
      offsetY: 0,
    }

    document.removeEventListener('mousemove', handleDragMove)
    document.removeEventListener('mouseup', stopDragging)
  }
}

// 下载图片
const downloadImage = () => {
  if (!imageLoaded.value || !originalImage.value) return

  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  if (!ctx) {
    ElMessage.error('无法创建画布上下文')
    return
  }

  const safeWidth = isNaN(imageWidth.value) ? 300 : imageWidth.value
  const safeHeight = isNaN(imageHeight.value) ? 200 : imageHeight.value
  canvas.width = safeWidth
  canvas.height = safeHeight

  const img = new Image()
  img.crossOrigin = 'anonymous'
  img.src = originalImage.value

  img.onload = () => {
    ctx.save()
    ctx.translate(canvas.width / 2, canvas.height / 2)
    ctx.rotate((rotation.value * Math.PI) / 180)
    if (flipState.value?.horizontal) ctx.scale(-1, 1)
    if (flipState.value?.vertical) ctx.scale(1, -1)
    ctx.drawImage(img, -canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height)
    ctx.restore()

    let canvasFilter = ''
    const safeBrightness = isNaN(brightness.value) ? 100 : brightness.value
    const safeContrast = isNaN(contrast.value) ? 100 : contrast.value
    const safeSaturation = isNaN(saturation.value) ? 100 : saturation.value

    if (filter.value && filter.value !== 'none') canvasFilter += `${filter.value} `
    canvasFilter += `brightness(${safeBrightness}%) `
    canvasFilter += `contrast(${safeContrast}%) `
    canvasFilter += `saturate(${safeSaturation}%)`

    ctx.filter = canvasFilter

    const tempCanvas = document.createElement('canvas')
    tempCanvas.width = canvas.width
    tempCanvas.height = canvas.height
    const tempCtx = tempCanvas.getContext('2d')
    if (!tempCtx) return

    tempCtx.save()
    tempCtx.translate(tempCanvas.width / 2, tempCanvas.height / 2)
    tempCtx.rotate((rotation.value * Math.PI) / 180)
    if (flipState.value?.horizontal) tempCtx.scale(-1, 1)
    if (flipState.value?.vertical) tempCtx.scale(1, -1)
    tempCtx.drawImage(
      img,
      -tempCanvas.width / 2,
      -tempCanvas.height / 2,
      tempCanvas.width,
      tempCanvas.height,
    )
    tempCtx.restore()

    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.filter = canvasFilter
    ctx.drawImage(tempCanvas, 0, 0)

    // 绘制文字图层
    textLayers.value.forEach((text) => {
      ctx.save()
      ctx.fillStyle = text.color || '#000000'
      ctx.font = `${text.size || 24}px sans-serif`
      ctx.textAlign = text.align || 'center'
      ctx.fillText(text.content || '', text.x || 0, text.y || 0)
      ctx.restore()
    })

    // 绘制贴图图层
    const drawStickersAndDownload = (index = 0) => {
      if (isNaN(index) || index >= stickerLayers.value.length) {
        try {
          const link = document.createElement('a')
          link.download = 'edited-image.png'
          link.href = canvas.toDataURL('image/png')
          link.click()
          addHistory('下载编辑后的图片')
        } catch (error) {
          console.error('下载失败:', error)
          ElMessage.error('图片下载失败')
        }
        return
      }

      const sticker = stickerLayers.value[index]
      if (!sticker || !sticker.src) {
        drawStickersAndDownload(index + 1)
        return
      }

      const stickerImg = new Image()
      stickerImg.crossOrigin = 'anonymous'
      stickerImg.src = sticker.src

      stickerImg.onload = () => {
        ctx.save()
        ctx.drawImage(
          stickerImg,
          sticker.x || 0,
          sticker.y || 0,
          sticker.size || 100,
          sticker.size || 100,
        )
        ctx.restore()
        drawStickersAndDownload(index + 1)
      }

      stickerImg.onerror = () => {
        console.error('贴图加载失败:', sticker.src)
        drawStickersAndDownload(index + 1)
      }
    }

    drawStickersAndDownload()
  }

  img.onerror = () => {
    ElMessage.error('图片加载失败，无法下载')
  }
}

// 添加历史记录
const addHistory = (action) => {
  if (!action) return

  // 确保history是数组
  if (!Array.isArray(history.value)) {
    history.value = []
  }

  // 处理索引异常情况
  if (isNaN(historyIndex.value) || historyIndex.value < -1) {
    historyIndex.value = -1
  }

  // 当有新操作时，清除当前索引之后的历史记录
  if (historyIndex.value < history.value.length - 1) {
    history.value = history.value.slice(0, historyIndex.value + 1)
  }

  const newState = saveCurrentState()
  history.value.push({
    action,
    time: new Date(),
    state: newState,
  })

  historyIndex.value = history.value.length - 1
}

// 保存当前状态
const saveCurrentState = () => {
  return {
    imageWidth: imageWidth.value,
    imageHeight: imageHeight.value,
    rotation: rotation.value,
    flipState: { ...flipState.value },
    brightness: brightness.value,
    contrast: contrast.value,
    saturation: saturation.value,
    filter: filter.value,
    textLayers: JSON.parse(JSON.stringify(textLayers.value)),
    stickerLayers: JSON.parse(JSON.stringify(stickerLayers.value)),
  }
}

// 撤销操作
const undo = () => {
  if (!Array.isArray(history.value) || history.value.length === 0) {
    console.log('无法撤销 - 历史记录不存在或为空')
    return
  }

  if (isNaN(historyIndex.value) || historyIndex.value < 0) {
    console.log('无法撤销 - 历史记录索引无效')
    historyIndex.value = 0
    return
  }

  console.log('尝试撤销 - 当前索引:', historyIndex.value, '历史长度:', history.value.length)

  if (historyIndex.value > 0) {
    historyIndex.value--
    const stateToRestore = history.value[historyIndex.value]?.state

    if (stateToRestore) {
      restoreState(stateToRestore)
      ElMessage.info('撤销操作')
    } else {
      console.error('找不到要恢复的状态')
    }
  } else {
    console.log('无法撤销 - 已到达历史记录起点')
  }
}

// 重做操作
const redo = () => {
  if (!Array.isArray(history.value) || history.value.length === 0) {
    console.log('无法重做 - 历史记录不存在或为空')
    return
  }

  if (isNaN(historyIndex.value) || historyIndex.value >= history.value.length) {
    console.log('无法重做 - 历史记录索引无效')
    historyIndex.value = history.value.length - 1
    return
  }

  console.log('尝试重做 - 当前索引:', historyIndex.value, '历史长度:', history.value.length)

  if (historyIndex.value < history.value.length - 1) {
    historyIndex.value++
    const stateToRestore = history.value[historyIndex.value]?.state

    if (stateToRestore) {
      restoreState(stateToRestore)
      ElMessage.info('重做操作')
    } else {
      console.error('找不到要恢复的状态')
    }
  } else {
    console.log('无法重做 - 已到达历史记录终点')
  }
}

// 恢复状态
const restoreState = (state) => {
  if (!state) return

  imageWidth.value = isNaN(state.imageWidth) ? 300 : Math.max(1, state.imageWidth)
  imageHeight.value = isNaN(state.imageHeight) ? 200 : Math.max(1, state.imageHeight)
  rotation.value = isNaN(state.rotation) ? 0 : state.rotation
  flipState.value = state.flipState || { horizontal: false, vertical: false }
  brightness.value = isNaN(state.brightness) ? 100 : state.brightness
  contrast.value = isNaN(state.contrast) ? 100 : state.contrast
  saturation.value = isNaN(state.saturation) ? 100 : state.saturation
  filter.value = state.filter || 'none'

  textLayers.value = Array.isArray(state.textLayers) ? state.textLayers : []
  stickerLayers.value = Array.isArray(state.stickerLayers) ? state.stickerLayers : []
}

// 格式化时间
const formatTime = (date) => {
  if (!(date instanceof Date)) return ''
  return date.toLocaleTimeString()
}

// 保存图片到服务器
const saveImageToServer = async () => {
  if (!imageLoaded.value || !originalImage.value) {
    ElMessage.warning('请先上传并编辑图片')
    return
  }

  try {
    ElMessage.info('正在保存图片到服务器...')

    // 创建画布并绘制图片（复用下载功能的绘制逻辑）
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    if (!ctx) {
      ElMessage.error('无法创建画布上下文')
      return
    }

    const safeWidth = isNaN(imageWidth.value) ? 300 : imageWidth.value
    const safeHeight = isNaN(imageHeight.value) ? 200 : imageHeight.value
    canvas.width = safeWidth
    canvas.height = safeHeight

    // 绘制基础图片
    const img = new Image()
    img.crossOrigin = 'anonymous'
    img.src = originalImage.value

    await new Promise((resolve, reject) => {
      img.onload = resolve
      img.onerror = reject
    })

    // 应用旋转和翻转
    ctx.save()
    ctx.translate(canvas.width / 2, canvas.height / 2)
    ctx.rotate((rotation.value * Math.PI) / 180)
    if (flipState.value?.horizontal) ctx.scale(-1, 1)
    if (flipState.value?.vertical) ctx.scale(1, -1)
    ctx.drawImage(img, -canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height)
    ctx.restore()

    // 应用滤镜效果
    let canvasFilter = ''
    const safeBrightness = isNaN(brightness.value) ? 100 : brightness.value
    const safeContrast = isNaN(contrast.value) ? 100 : contrast.value
    const safeSaturation = isNaN(saturation.value) ? 100 : saturation.value

    if (filter.value && filter.value !== 'none') canvasFilter += `${filter.value} `
    canvasFilter += `brightness(${safeBrightness}%) contrast(${safeContrast}%) saturate(${safeSaturation}%)`

    // 创建临时画布处理滤镜
    const tempCanvas = document.createElement('canvas')
    tempCanvas.width = canvas.width
    tempCanvas.height = canvas.height
    const tempCtx = tempCanvas.getContext('2d')
    if (tempCtx) {
      tempCtx.filter = canvasFilter
      tempCtx.drawImage(canvas, 0, 0)
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(tempCanvas, 0, 0)
    }

    // 绘制文字图层
    textLayers.value.forEach((text) => {
      ctx.save()
      ctx.fillStyle = text.color || '#000000'
      ctx.font = `${text.size || 24}px sans-serif`
      ctx.textAlign = text.align || 'center'
      ctx.fillText(text.content || '', text.x || 0, text.y || 0)
      ctx.restore()
    })

    // 绘制贴图图层
    await Promise.all(
      stickerLayers.value.map((sticker) => {
        return new Promise((resolve) => {
          const stickerImg = new Image()
          stickerImg.crossOrigin = 'anonymous'
          stickerImg.src = sticker.src
          stickerImg.onload = () => {
            ctx.save()
            ctx.drawImage(
              stickerImg,
              sticker.x || 0,
              sticker.y || 0,
              sticker.size || 100,
              sticker.size || 100,
            )
            ctx.restore()
            resolve()
          }
          stickerImg.onerror = () => resolve() // 忽略加载失败的贴图
        })
      }),
    )

    // 将canvas转换为 file对象
    const blob = await new Promise((resolve) => {
      canvas.toBlob((blob) => resolve(blob), 'image/png')
    })

    const file = new File([blob], 'image.png', { type: blob.type })

    if (!blob) {
      ElMessage.error('无法将图片转换为文件')
      return
    }

    console.log('上传参数:', file)

    // 调用上传API
    const response = await uploadPictureAPI(file, saveForm)
    showSaveDialog.value = false
    ElMessage.success('图片已成功保存到服务器')

    addHistory('保存图片到服务器')
    console.log('服务器返回结果:', response)
  } catch (error) {
    console.error('保存图片失败:', error)
    ElMessage.error('保存图片失败: ' + (error.message || '未知错误'))
  }
}

// 初始化历史记录系统
onMounted(() => {
  console.log('图片编辑器已初始化')
  if (!Array.isArray(history.value)) {
    history.value = []
  }
  if (isNaN(historyIndex.value) || historyIndex.value < -1) {
    historyIndex.value = -1
  }
})
</script>

<style scoped>
/* 基础样式保持不变 */
.image-editor-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.editor-toolbar-btns {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo {
  font-size: 1.5rem;
  font-weight: bold;
  color: #1890ff;
}

.upload-btn {
  margin-right: 10px;
}

.editor-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.editor-toolbar {
  background-color: #f5f7fa;
  border-right: 1px solid #e4e7ed;
  padding: 15px;
  overflow-y: auto;
}

.edited-image {
  position: relative;
  background-color: #f9f9f9;
  border-radius: 4px;
  min-height: 200px;
}

.text-layer {
  z-index: 10;
  pointer-events: auto;
  cursor: pointer;
}

.sticker-layer {
  z-index: 20;
  pointer-events: auto;
}

.original-image {
  z-index: 1;
  position: relative;
}

/* 历史记录样式优化 */
.inactive-history {
  opacity: 0.5;
}

/* 历史记录文字样式 - 新增部分 */
.history-action {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 其他样式保持不变 */
.toolbar-tabs {
  height: 100%;
}

.tool-section {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #e4e7ed;
}

.tool-section:last-child {
  border-bottom: none;
}

.tool-section h3 {
  margin-bottom: 15px;
  font-size: 1rem;
  color: #1f2329;
}

.el-input-number {
  margin-bottom: 10px;
  width: 100%;
}

.rotation-controls,
.flip-controls {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 10px;
}

.slider-value {
  display: block;
  text-align: right;
  margin-top: -15px;
  margin-bottom: 10px;
  font-size: 0.85rem;
  color: #666;
}

.sticker-library {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.sticker-item {
  width: 60px;
  height: 60px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.2s;
}

.sticker-item.selected {
  border: 2px solid #1890ff;
}

.sticker-thumb {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.added-texts,
.added-stickers {
  margin-top: 20px;
}

.text-item,
.sticker-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.empty-text {
  text-align: center;
  color: #999;
  padding: 10px 0;
}

.editor-workspace {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  background-color: #f0f2f5;
}

.workspace-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.placeholder-container {
  width: 100%;
  max-width: 800px;
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.image-container {
  position: relative;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.sticker-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  cursor: pointer;
}

.editor-history {
  background-color: #f5f7fa;
  border-left: 1px solid #e4e7ed;
  padding: 15px;
  /* 添加滚动条 */
  height: 100%;
  overflow-y: auto;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-controls {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 15px;
}

.el-timeline {
  padding-left: 10px;
}

.el-timeline-item__timestamp {
  font-size: 0.75rem !important;
}
</style>
